import axios from 'axios'
import { ACCESS_TOKEN } from '@/utils/vars'
// import { useMappedState } from "redux-react-hook"
import { message } from 'antd';
import { getToken } from '@/utils/auth'

function errorStatus(error) {
  if (!error || !error.response) return
  switch (error.response.status) {
    case 400:
      error.message = "请求错误(400)";
      break;
    case 401:
      error.message = "未授权,请登录(401)";
      break;
    case 403:
      error.message = "拒绝访问(403)";
      break;
    case 404:
      error.message = `请求地址出错: ${error.response.config.url}`;
      break;
    case 405:
      error.message = "请求方法未允许(405)";
      break;
    case 408:
      error.message = "请求超时(408)";
      break;
    case 500:
      error.message = "服务器内部错误(500)";
      break;
    case 501:
      error.message = "服务未实现(501)";
      break;
    case 502:
      error.message = "网络错误(502)";
      break;
    case 503:
      error.message = "服务不可用(503)";
      break;
    case 504:
      error.message = "网络超时(504)";
      break;
    case 505:
      error.message = "HTTP版本不受支持(505)";
      break;
    default:
      error.message = `连接错误: ${error.message}`;
  }
}

/**
 * @param {String} baseURL 请求前缀
 * @param {Number} timeout 超时时长
 * @param {Boolean} withCredentials 添加cookie
 * @returns {Axios Instance}
 */
const createSever = (baseURL, timeout = 5 * 1000, withCredentials = true) => {
  const instance = axios.create({ baseURL, withCredentials, timeout })
  instance.interceptors.request.use(config => {
    const token = getToken()
    if (token) config.headers[ACCESS_TOKEN] = token
    // 禁止ie浏览器请求缓存
    if (!!window.ActiveXObject || 'ActiveXObject' in window) {
      config.headers['cache-control'] = 'no-cache'
      config.headers['Pragma'] = 'no-cache'
    }
    return config
  }, e => Promise.reject(e))

  instance.interceptors.response.use(async (response) => {
    const { headers, data } = response
    const contentType = headers['content-type']
    // 如果不是json则直接返回data
    if (contentType && !/json/.test(contentType)) return data
    if (data instanceof Blob && /json/.test(data.type))
      return JSON.parse(await data.text())
    if (+data.code === 0) return data
    const errMsg = data.message || '接口没有返回任何消息，请联系管理员！'
    message.error(errMsg);
    return Promise.reject(new Error(errMsg))
  }, error => {
    errorStatus(error)
    const { status } = error.response
    // 鉴权需要登录
    if (status === 401) {
      return
    }
    message.error(error.message);
    return Promise.reject(error)
  })
  return instance
}

export default createSever(process.env.REACT_APP_BASE_API)
